package com.example.administrator.zhongyichou.utils;

import android.os.Handler;
import android.os.Message;

import com.example.administrator.zhongyichou.Bean.PayServiceBean;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WebServiceUtils {
    public static final String WEB_SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";


    // 含有3个线程的线程池
    private static final ExecutorService executorService = Executors
            .newFixedThreadPool(3);

    // 命名空间
    private static final String NAMESPACE = "http://payat.ips.com.cn/WebService/Scan";

//    /**
//     *
//     * @param url
//     *            WebService服务器地址
//     * @param methodName
//     *            WebService的调用方法名
//     * @param properties
//     *            WebService的参数
//     * @param webServiceCallBack
//     *            回调接口
//     */
//    public static void callWebService(String url, final String methodName,
//                                      HashMap<String, String> properties,
//                                      final WebServiceCallBack webServiceCallBack) {
//        // 创建HttpTransportSE对象，传递WebService服务器地址
//        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
//        // 创建SoapObject对象
//        SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
//
//        // SoapObject添加参数
//        if (properties != null) {
//            for (Iterator<Map.Entry<String, String>> it = properties.entrySet()
//                    .iterator(); it.hasNext();) {
//                Map.Entry<String, String> entry = it.next();
//                soapObject.addProperty(entry.getKey(), entry.getValue());
//            }
//        }
//
//        // 实例化SoapSerializationEnvelope，传入WebService的SOAP协议的版本号
//        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
//                SoapEnvelope.VER11);
//        // 设置是否调用的是.Net开发的WebService
//        soapEnvelope.setOutputSoapObject(soapObject);
//        soapEnvelope.dotNet = true;
//        httpTransportSE.debug = true;
//
//        // 用于子线程与主线程通信的Handler
//        final Handler mHandler = new Handler() {
//
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                // 将返回值回调到callBack的参数中
//                webServiceCallBack.callBack((SoapObject) msg.obj);
//            }
//
//        };
//
//        // 开启线程去访问WebService
//        executorService.submit(new Runnable() {
//
//            @Override
//            public void run() {
//                SoapObject resultSoapObject = null;
//                try {
//                    httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
//                    if (soapEnvelope.getResponse() != null) {
//                        // 获取服务器响应返回的SoapObject
//                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
//                    }
//                } catch (HttpResponseException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (XmlPullParserException e) {
//                    e.printStackTrace();
//                } finally {
//                    // 将获取的消息利用Handler发送到主线程
//                    mHandler.sendMessage(mHandler.obtainMessage(0,
//                            resultSoapObject));
//                }
//            }
//        });
//    }


    /**
     * @param url                WebService服务器地址
     * @param methodName         WebService的调用方法名
     * @param webServiceCallBack 回调接口
     */
    public static void callWebService(String url, final String methodName,
                                      PayServiceBean mGsonBaseProtocol,
                                      final WebServiceCallBack webServiceCallBack) {


        String content = "<Ips> \n" +
                "<GateWayReq> \n" +
                " <head> \n" +
                " <Version>&Version</Version> \n" +
                " <MerCode>&MerCode</MerCode> \n" +
                " <MerName>&MerName</MerName> \n" +
                " <Account>&Account</Account> \n" +
                " <MsgId>&MsgId</MsgId> \n" +
                " <ReqDate>&ReqDate</ReqDate> \n" +
                " <Signature>&Signature</Signature> \n" +
                " </head> \n" +
                " <body> \n" +
                " <MerBillNo>&MerBillNo</MerBillNo> \n" +
                " <Service>&Service</Service> \n" +
                " <GatewayType>&GatewayType</GatewayType> \n" +
                " <Date>&Date</Date> \n" +
                " <CurrencyType>&CurrencyType</CurrencyType> \n" +
                " <Amount>&Amount</Amount> \n" +
                " <Lang>&Lang</Lang> \n" +
                " <Attach>&Attach</Attach> \n" +
                " <RetEncodeType>&RetEncodeType</RetEncodeType> \n" +
                " <DeviceInfo>&DeviceInfo</DeviceInfo> \n" +
                " <DeviceType>&DeviceType</DeviceType> \n" +
                " <MchCreateIp>&MchCreateIp</MchCreateIp> \n" +
                " <ServerUrl>&ServerUrl</ServerUrl> \n" +
                " <BillEXP>&BillEXP</BillEXP> \n" +
                " <GoodsName>&GoodsName</GoodsName> \n" +
                "<AppID>&AppID</ AppID > \n" +
                "</body> \n" +
                "</GateWayReq> \n" +
                "</Ips> ";


        // 创建HttpTransportSE对象，传递WebService服务器地址
        final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
        // 创建SoapObject对象
        SoapObject soapObject = new SoapObject(NAMESPACE, methodName);
//
//        // SoapObject添加参数
//        if (mGsonBaseProtocol != null) {
//            SoapObject soapObjectIps = new SoapObject(NAMESPACE, "");
//            SoapObject soapObjectGateWayReq = new SoapObject(NAMESPACE, "");
//            SoapObject soapObjectHead = new SoapObject(NAMESPACE, "");
//            SoapObject soapObjectBody = new SoapObject(NAMESPACE, "");
//
//            soapObjectHead.addProperty("Version", mGsonBaseProtocol.getData().getVersion());
//            soapObjectHead.addProperty("MerCode", mGsonBaseProtocol.getData().getMerCode());
//            soapObjectHead.addProperty("Account", mGsonBaseProtocol.getData().getAccount());
//            soapObjectHead.addProperty("ReqDate", mGsonBaseProtocol.getData().getReqDate());
//            soapObjectHead.addProperty("Signature", mGsonBaseProtocol.getData().getSignature());
//
//            soapObjectBody.addProperty("MerBillNo", mGsonBaseProtocol.getData().getMerBillNo());
//            soapObjectBody.addProperty("Service", mGsonBaseProtocol.getData().getService());
//            soapObjectBody.addProperty("GatewayType", mGsonBaseProtocol.getData().getGatewayType());
//            soapObjectBody.addProperty("Date", mGsonBaseProtocol.getData().getDate());
//            soapObjectBody.addProperty("CurrencyType", mGsonBaseProtocol.getData().getCurrencyType());
//            soapObjectBody.addProperty("Amount", mGsonBaseProtocol.getData().getAmount());
//            soapObjectBody.addProperty("RetEncodeType", mGsonBaseProtocol.getData().getRetEncodeType());
//            soapObjectBody.addProperty("DeviceType", "ANDROID");
//            soapObjectBody.addProperty("MchCreateIp", mGsonBaseProtocol.getData().getMchCreateIp());
//            soapObjectBody.addProperty("ServerUrl", mGsonBaseProtocol.getData().getServerUrl());
//            soapObjectBody.addProperty("GoodsName", mGsonBaseProtocol.getData().getGoodsName());
//            soapObjectBody.addProperty("AppID", mGsonBaseProtocol.getData().getAppID());
//
//
//            soapObjectGateWayReq.addProperty("head", soapObjectHead);
//            soapObjectGateWayReq.addProperty("body", soapObjectBody);
//            soapObjectIps.addProperty("GateWayReq", soapObjectGateWayReq);
//            soapObject.addProperty("Ips", soapObjectIps);
//
////            for (Iterator<Map.Entry<String, String>> it = properties.entrySet()
////                    .iterator(); it.hasNext();) {
////                Map.Entry<String, String> entry = it.next();
////                soapObject.addProperty(entry.getKey(), entry.getValue());
////            }
//        }
//
//
        content.replace("&Version", mGsonBaseProtocol.getData().getVersion());
        content.replace("&MerCode", mGsonBaseProtocol.getData().getMerCode());
        content.replace("&Account", mGsonBaseProtocol.getData().getAccount());
        content.replace("&ReqDate", mGsonBaseProtocol.getData().getReqDate());
        content.replace("&Signature", mGsonBaseProtocol.getData().getSignature());

        content.replace("&MerBillNo", mGsonBaseProtocol.getData().getMerBillNo());
        content.replace("&Service", mGsonBaseProtocol.getData().getService());
        content.replace("&GatewayType", mGsonBaseProtocol.getData().getGatewayType());
        content.replace("&Date", mGsonBaseProtocol.getData().getDate());
        content.replace("&CurrencyType", mGsonBaseProtocol.getData().getCurrencyType());
        content.replace("&DeviceType", "ANDROID");
        content.replace("&MchCreateIp", mGsonBaseProtocol.getData().getMchCreateIp());
        content.replace("&ServerUrl", mGsonBaseProtocol.getData().getServerUrl());
        content.replace("&GoodsName", mGsonBaseProtocol.getData().getGoodsName());
        content.replace("&AppID", mGsonBaseProtocol.getData().getAppID());


        // 实例化SoapSerializationEnvelope，传入WebService的SOAP协议的版本号
        final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        // 设置是否调用的是.Net开发的WebService
        soapObject.addProperty("scanPayReq", content);
        soapEnvelope.setOutputSoapObject(soapObject);
//        soapEnvelope.xsd=NAMESPACE;
//        soapEnvelope.bodyOut = content;
//        soapEnvelope.dotNet = true;
        httpTransportSE.debug = true;

        // 用于子线程与主线程通信的Handler
        final Handler mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                // 将返回值回调到callBack的参数中
                webServiceCallBack.callBack((SoapObject) msg.obj);
            }

        };

        // 开启线程去访问WebService
        executorService.submit(new Runnable() {

            @Override
            public void run() {
                SoapObject resultSoapObject = null;
                try {
                    httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
                    if (soapEnvelope.getResponse() != null) {
                        // 获取服务器响应返回的SoapObject
                        resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
                    }
                } catch (HttpResponseException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } finally {
                    // 将获取的消息利用Handler发送到主线程
                    mHandler.sendMessage(mHandler.obtainMessage(0,
                            resultSoapObject));
                }
            }
        });
    }

    /**
     * @author xiaanming
     */
    public interface WebServiceCallBack {
        public void callBack(SoapObject result);
    }

}